package com.log4jviewer;

import java.io.IOException;
import java.net.URL;

import org.apache.log4j.PropertyConfigurator;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.log4jviewer.ui.preferences.DefaultPreferenceInitializer;

public class Activator extends AbstractUIPlugin {

    private static final String LOG4J_PROPERTIES_PATH = "config/log4j.properties";

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static Activator plugin;

    private IPreferenceStore preferenceStore;

    public Activator() {
        plugin = this;
    }

    public static Activator getInstance() {
        return plugin;
    }

    public String getPluginId() {
        return plugin.getBundle().getSymbolicName();
    }

    @Override
    public IPreferenceStore getPreferenceStore() {
        return preferenceStore;
    }

    @Override
    public void start(final BundleContext context) throws Exception {
        super.start(context);
        PropertyConfigurator.configure(getAbsolutePath(LOG4J_PROPERTIES_PATH));
        logger.info("Log4j configuration was successfully loaded.");

        initializeStore();
    }

    @Override
    public void stop(final BundleContext context) throws Exception {
        plugin = null;
        super.stop(context);
    }

    private void initializeStore() {
        preferenceStore = super.getPreferenceStore();
        DefaultPreferenceInitializer prefsInit = new DefaultPreferenceInitializer();
        prefsInit.initializeDefaultPreferences(preferenceStore);
    }

    public static String getAbsolutePath(final String filePath) throws IOException {
        URL confUrl = getInstance().getBundle().getEntry(filePath);
        return FileLocator.toFileURL(confUrl).getFile();
    }

    public static ImageDescriptor getImageDescriptor(final String path) {
        return imageDescriptorFromPlugin(plugin.getPluginId(), path);
    }
}
